package com.bbs.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.bbs.entity.Article;
import com.bbs.entity.Message;
import com.bbs.entity.User;
import com.bbs.util.DBHelp;
import com.bbs.util.Page;
import com.bbs.util.RowMapper;

public class MessageDao {
	private DBHelp<Message> dh = new DBHelp<Message>();
	
	/**
	 * 添加消息
	 * @param u
	 * @param a
	 * @param content
	 */
	public void save(User u,Article a,String content,String date){
		String sql = "INSERT INTO t_message(content,t_user_id,to_user_id,createdate,state) VALUES(?,?,?,?,0)";
		dh.update(sql, content,u.getId(),a.getUser().getId(),date);
	}

	/**
	 * 用用户id找到未读消息
	 * @param id
	 * @return
	 */
	public List<Message> findNoReadByUid(int id,Page page) {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT m.id,m.content,t_user_id,to_user_id,m.state,m.createdate,u.id AS userid,u.username,");
		sql.append("u.userpwd,u.score,u.level,u.headpic,u.createdate as usercreatedate,u.email,u.role,u.state AS userstate,");
		sql.append("u.active FROM t_message AS m  LEFT JOIN t_user AS u ON t_user_id = u.id WHERE m.state = 0 and to_user_id = ? limit ?,?");
		return dh.queryForList(sql.toString(), new MessageMapper(), id,page.getStartNum(),page.getPageSize());
	}
	
	public void update(){
		String sql = "UPDATE t_message SET state = 1 WHERE state = 0";
		dh.update(sql);
	}

	public int getNoReadCountByuid(int id) {
		String sql = "SELECT COUNT(*) FROM t_message WHERE to_user_id = ? AND state = 0";
		return dh.queryForCount(sql, id);
	}
}

class MessageMapper implements RowMapper<Message>{
	public Message maprow(ResultSet rs) throws SQLException {
		Message m = new Message();
		m.setContent(rs.getString("content"));
		m.setCreatedate(rs.getString("createdate"));
		m.setId(rs.getInt("id"));
		m.setState(rs.getBoolean("state"));
		
		User u = new User();
		u.setActive(rs.getInt("active"));
		u.setCreatedate(rs.getString("usercreatedate"));
		u.setEmail(rs.getString("email"));
		u.setHeadpic(rs.getString("headpic"));
		u.setId(rs.getInt("userid"));
		u.setLevel(rs.getInt("level"));
		u.setRole(rs.getInt("role"));
		u.setScore(rs.getInt("score"));
		u.setState(rs.getBoolean("userstate"));
		u.setUsername(rs.getString("username"));
		u.setUserpwd(rs.getString("userpwd"));
		m.setFuser(u);
		return m;
	}
}
